package com.zookeeper.dome;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.function.Consumer;

public class DistributeServer {
    private String connectString = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        //1链接zookeeper集群
        DistributeServer distributeServer = new DistributeServer();
        distributeServer.getConnect();

        //2注册节点
        distributeServer.regist(args[0]);

        //3业务逻辑处理
        distributeServer.busServer();
    }

    private void busServer() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws KeeperException, InterruptedException {
        String s = zooKeeper.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

    }

    private void getConnect() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
             /*   try {
                    System.out.println("=================start==================");
                    List<String> children = zooKeeper.getChildren("/", true);
                    for (String child : children) {
                        System.out.println(child);
                    }
                    System.out.println("=================end==================");
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
            }
        });
    }
}
